﻿using System;
using System.Linq;
using System.Collections.Generic;
using TweetSharp.Twitter.Extensions;
using TweetSharp.Twitter.Fluent;
using TweetSharp.Twitter.Model;

namespace Halfwit.Pollers
{
    public class SearchPoller : TwitterPoller
    {
        public SearchPoller(Func<String> phrase, Action<TwitterPoller, TwitterResult> callback)
            : base(callback)
        {
            _phrase = phrase;

            Description = "Search";
        }

        private string _lastPhrase;
        private Func<String> _phrase;

        protected override bool CanPoll()
        {
            return !string.IsNullOrEmpty(_phrase());
        }

        protected override ITwitterLeafNode CreateRequest(IFluentTwitter twitter)
        {
            var phrase = _phrase();

            // search anew if the phrase has changed since last time
            if (phrase != _lastPhrase) Reset();

            _lastPhrase = phrase;

            var request = twitter.Search().Query();
            //if (phrase.StartsWith("#"))
            //{
                request = request.Containing(phrase.Replace("#", "%2523"));
            //}
            //else
            //{
            //    request = request.Containing(phrase);
            //}

            if (LastId.HasValue)
            {
                request = request.Since(LastId.Value);
            }
            else
            {
                request = request.Take(Properties.Settings.Default.MaxTweets);
            }
            return request;
        }

        protected override void OnSuccessfulRequest(TwitterResult result)
        {
            var searchResult = result.AsSearchResult();
            if (searchResult == null) return;

            Description = "Search for " + System.Web.HttpUtility.UrlDecode(searchResult.Query);

            var tweets = searchResult.Statuses;
            if (tweets == null || tweets.Count() == 0) return;

            LastId = tweets.Max(t => t.Id);
        }

        public override IEnumerable<TwitterStatus> ToStatuses(TwitterResult result)
        {
            var searchResult = result.AsSearchResult();
            if (searchResult == null) return Enumerable.Empty<TwitterStatus>();

            return searchResult.Statuses.Select(s =>
                            new TwitterStatus
                            {
                                Id = s.Id,
                                CreatedDate = s.CreatedDate,
                                Location = s.GeoLocation,
                                Source = HalfwitConstants.SearchResultSource,
                                Text = s.Text,
                                User = new TwitterUser { ProfileImageUrl = s.ProfileImageUrl, ScreenName = s.FromUserScreenName },
                            });
        }
    }
}
